package com.taobao.shopcart.api;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taobao.base.model.RestResponse;
import com.taobao.base.model.TokenResponse;
import com.taobao.base.model.TokenUser;
import com.taobao.publisher.MqSendService;
import com.taobao.shopcart.feignclient.AuthServiceClient;
import com.taobao.shopcart.feignclient.HomeServiceClient;
import com.taobao.shopcart.model.dto.CartDto;
import com.taobao.shopcart.model.dto.GoodsDetailsDto;
import com.taobao.shopcart.model.dto.OrderDto;
import com.taobao.shopcart.model.po.Cart;
import com.taobao.shopcart.model.po.Orders;
import com.taobao.shopcart.service.CartService;
import com.taobao.shopcart.service.OrderService;
import com.taobao.shopcart.service.ShopCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@CrossOrigin
public class ShopcartController {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    private CartService cartService;
    @Autowired
    private MqSendService mqSendService;
    @Autowired
    private ShopCartService shopCartService;
    @Autowired
    private AuthServiceClient authServiceClient;
    @Autowired
    private HomeServiceClient homeServiceClient;
    @Autowired
    private OrderService orderService;

    //测试MQ发送消息
    @GetMapping("/test")
    public void test() {

        System.out.println("dddddd");
        mqSendService.testSendObject();
    }

    /**
     * 获取所有订单
     */
    @GetMapping("/getAllOrder")
    public RestResponse<List<Orders>> getAllOrder(HttpServletRequest request) {
        TokenUser tokenUser = getTokenUser(request);

        RestResponse<List<Orders>> allOrder = orderService.getAllOrder(tokenUser.getUserId());
        return allOrder;
    }
    /**
     * 根据cartId删除
     */
    @DeleteMapping("/deleteCart/{cartId}")
    public RestResponse<String> deleteCart(@PathVariable("cartId") int cartId) {
        return cartService.deleteCart(cartId);
    }

    /**
     * 获取待发货订单
     */
    @GetMapping("/getWaitSendOrder")
    public RestResponse<List<OrderDto>> getWaitSendOrder(HttpServletRequest request) {
        // 获取当前用户信息
        TokenUser tokenUser = getTokenUser(request);
        return orderService.getUnshippedOrder(tokenUser.getUserId());
    }

    /**
     * 待付款订单
     */
    @GetMapping("/getWaitPayOrder")
    public RestResponse<List<OrderDto>> getUnpaidOrder(HttpServletRequest request) {

        // 获取当前用户信息
        TokenUser tokenUser = getTokenUser(request);
        RestResponse<List<OrderDto>> unpaidOrder = orderService.getUnpaidOrder(tokenUser.getUserId());

        return unpaidOrder;

    }

    /**
     * 选中的购物车id存放到redis
     */
    @PostMapping("/redisSet")
    public RestResponse<String> redisSet(@RequestBody List<Integer> selectedCartIds, HttpServletRequest request) {
        TokenUser tokenUser = getTokenUser(request);

        // 使用 ObjectMapper 将 List<Integer> 序列化为 JSON 字符串
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String cartIdsJson = objectMapper.writeValueAsString(selectedCartIds);

            // 存储到 Redis，设置过期时间为 10 秒
            redisTemplate.opsForValue().set(tokenUser.getUserId() + "cartIds", cartIdsJson, 5, TimeUnit.SECONDS);
            return RestResponse.success("数据存储成功！");
        } catch (JsonProcessingException e) {
            // 捕获序列化异常
            return RestResponse.validfail("数据序列化失败：" + e.getMessage());
        }
    }

    /**
     * redis
     */
    @GetMapping("/redisGet")
    public RestResponse<List<Integer>> redisGet(HttpServletRequest request) {
        // 获取当前用户信息
        TokenUser tokenUser = getTokenUser(request);
        // 从 Redis 中获取存储的 JSON 字符串
        String cartIdsJson = (String) redisTemplate.opsForValue().get(tokenUser.getUserId() + "cartIds");

        if (cartIdsJson == null) {
            return RestResponse.validfail("未找到对应的数据！");
        }
        // 使用 ObjectMapper 将 JSON 字符串反序列化为 List<Integer>
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            List<Integer> selectedCartIds = objectMapper.readValue(cartIdsJson, new TypeReference<List<Integer>>() {
            });
            return RestResponse.success(selectedCartIds);
        } catch (JsonProcessingException e) {
            // 捕获反序列化异常
            return RestResponse.validfail("数据反序列化失败：" + e.getMessage());
        }
    }

    /**
     * 添加购物车
     */
    @PostMapping("/addCart")
    public RestResponse<String> addCart(@RequestBody CartDto cartDto, HttpServletRequest request) {
        TokenUser tokenUser = getTokenUser(request);

        return cartService.addCart(cartDto, tokenUser.getUserId());
    }

    /**
     * 根据id查询商品title
     */
    @GetMapping("/getProductTitle/{goodsIdList}")
    public RestResponse<List<GoodsDetailsDto>> getProductTitle(@PathVariable("goodsIdList") int goodsIdList[]) {

        List<GoodsDetailsDto> goodsDetailsDtoList = new ArrayList<>();
        for (int i : goodsIdList) {
            RestResponse<GoodsDetailsDto> goodsDetail = homeServiceClient.getGoodsDetail(i);
            goodsDetailsDtoList.add(goodsDetail.getResult());
        }
        System.out.println(goodsDetailsDtoList);
        return RestResponse.success(goodsDetailsDtoList);
    }

    /**
     * 根据用户id查询购物车信息
     */
    @GetMapping("/getCart")
    public RestResponse<List<Cart>> getCart(HttpServletRequest request) {
        TokenUser tokenUser = getTokenUser(request);
        return cartService.getCart(tokenUser.getUserId());
    }

    /**
     * 根据用户id查询购物车信息(Feign专用)
     */
    @GetMapping("/getCart/{userId}")
    public RestResponse<List<Cart>> getCart(@PathVariable("userId") int userId) throws JsonProcessingException {

        RestResponse<List<Cart>> cart = cartService.getCart(userId);
        // 打印对象内容
        System.out.println("序列化前的对象: " + cart);

// 序列化为 JSON
        String json = objectMapper.writeValueAsString(cart);
        System.out.println("序列化后的 JSON: " + json);
        return cart;
    }

    /**
     * 通过cratIds 获取goodsIdList
     */
    @PostMapping("/cartToGoodsId")
    public RestResponse<List<Integer>> cartToGoosd(@RequestBody List<Integer> selectedCartIds) {
        return cartService.cartToGoosd(selectedCartIds);
    }

    /**
     * 通过cratIds 获取goods数量
     */
    @PostMapping("/quantity")
    public RestResponse<List<Integer>> quantity(@RequestBody List<Integer> selectedCartIds) {
        return cartService.quantity(selectedCartIds);
    }

    /**
     * 解析token 获取用户信息
     */
    private TokenUser getTokenUser(HttpServletRequest request) {
        // 从请求头中获取 Authorization 字段
        TokenUser tokenUser = null;
        String authorizationHeader = request.getHeader("Authorization");
        // 检查是否包含 Bearer Token
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7); // 去掉 "Bearer " 前缀
            TokenResponse tokenResponse = authServiceClient.checkToken(token);
            String jsonString = tokenResponse.getUser_name();
            // 转TokeUser对象
            try {
                tokenUser = objectMapper.readValue(jsonString, TokenUser.class);
                System.out.println(tokenUser);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return tokenUser;
    }

    /**
     * 根据用户id查询订单列表
     *
     * @param request
     * @return
     */
    @GetMapping("/queryOrder")
    public RestResponse<List<Orders>> queryOrder(HttpServletRequest request) {

        TokenUser tokenUser = getTokenUser(request);

        return shopCartService.queryOrder(tokenUser.getUserId());
    }

    // 提交订单
    @PostMapping("/submitOrder")
    public RestResponse<Long> submitOrder(@RequestBody OrderDto orderDto, HttpServletRequest request) {

        TokenUser tokenUser = null;
        RestResponse<Long> stringRestResponse;

        // 从请求头中获取 Authorization 字段
        String authorizationHeader = request.getHeader("Authorization");
        // 检查是否包含 Bearer Token
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7); // 去掉 "Bearer " 前缀
            TokenResponse tokenResponse = authServiceClient.checkToken(token);
            String jsonString = tokenResponse.getUser_name();
            // 转TokeUser对象
            try {
                tokenUser = objectMapper.readValue(jsonString, TokenUser.class);
                System.out.println(tokenUser);
                // 防止重复下单
                String key = tokenUser.getUsername();
                String value = tokenUser.getUsername() + tokenUser.getUserId() + orderDto.getTotalPrice();
                String temp = (String) redisTemplate.opsForValue().get(key);
                if (temp != null) {
                    if (temp.equals(value)) {
                        return RestResponse.validfail("重复下单");
                    }
                }
                redisTemplate.opsForValue().set(key, value, 10, TimeUnit.SECONDS); // 10秒后过期
            } catch (Exception e) {
                e.printStackTrace();
                log.error("Failed to parse JSON string to TokenUser object: {}", jsonString);
            }
        } else {
            System.err.println("No valid token found in the Authorization header.");
        }

        if (tokenUser == null) {
            return RestResponse.validfail("用户未登录");
        }
        stringRestResponse = shopCartService.submitOrder(orderDto, tokenUser.getUserId());

        return stringRestResponse;
    }
}
